package com.day4;

import com.day4.protocal.command.*;
import com.day4.serializedev.Serializer;
import com.day4.serializedev.impl.JSONSerializer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

import java.util.HashMap;
import java.util.Map;

import static com.day4.protocal.command.Command.*;

/**
 * @author leonard
 * @Description 依赖封装的协议和序列化算法
 * 将数据编码和解码的工具类
 * @date 2021-05-24 12:44
 */
public class PacketCodeC {

    private static final int MAGIC_NUMBER = 0x12345678;
    //存储通信对象定义,里面存有指令和对应的存放数据
    private static final Map<Byte, Class<? extends Packet>> packetTypeMap = new HashMap<>();
    //存储序列化算法
    private static final Map<Byte, Serializer> serializerMap = new HashMap<>();

    //改成单例节约性能 by zoulj
    public static final PacketCodeC INSTANCE = new PacketCodeC();
    private PacketCodeC(){}

    static {
        packetTypeMap.put(LOGIN_REQUEST, LoginRequestPacker.class);
        packetTypeMap.put(LOGIN_RESPONSE, LoginResponsePacket.class);
        packetTypeMap.put(MESSAGE_REQUEST, MessageRequestPacket.class);
        packetTypeMap.put(MESSAGE_RESPONSE, MessageResponsePacket.class);
        Serializer serializer = new JSONSerializer();
        serializerMap.put(serializer.getSerializerAlgorithm(), serializer);
    }



    //将packet通信对象存入到ByteBuf中
    public ByteBuf encode(ByteBufAllocator byteBufAllocator,Packet packet) {
        // 1. 创建 ByteBuf 对象
        // 这里指定byteBuf为传入的ByteBuf的内存管理器
        ByteBuf byteBuf = byteBufAllocator.ioBuffer();
        //ByteBuf byteBuf = ByteBufAllocator.DEFAULT.ioBuffer();
        // 2. 序列化 Java 对象
        byte[] bytes = Serializer.DEFAULT.serialze(packet);

        // 3. 实际编码过程
        byteBuf.writeInt(MAGIC_NUMBER);
        byteBuf.writeByte(packet.getVersion());
        //这里的算法可以用入参的形式写活
        byteBuf.writeByte(Serializer.DEFAULT.getSerializerAlgorithm());

        byteBuf.writeByte(packet.getCommand());
        byteBuf.writeInt(bytes.length);
        byteBuf.writeBytes(bytes);

        return byteBuf;
    }

    public Packet decode(ByteBuf byteBuf) {
        // 跳过 magic number
        byteBuf.skipBytes(4);

        // 跳过版本号
        byteBuf.skipBytes(1);

        // 序列化算法标识
        byte serializeAlgorithm = byteBuf.readByte();

        // 指令
        byte command = byteBuf.readByte();

        // 数据包长度
        int length = byteBuf.readInt();

        byte[] bytes = new byte[length];
        byteBuf.readBytes(bytes);

        //获取对于的通信对象定义
        Class<? extends Packet> clazzType = packetTypeMap.get(command);
        //获取序列化算法
        Serializer serializer = serializerMap.get(serializeAlgorithm);

        if (clazzType != null && serializer != null) {
            //通过序列化算法和编码对象进行解码
            return serializer.deserialze(clazzType, bytes);
        }

        return null;
    }
}
